﻿namespace 线程等待和唤醒2
{
    internal class Program
    {
        // 定义一个自动重置的事件  
        static AutoResetEvent autoEvent = new AutoResetEvent(false);

        static void Main()
        {
            Thread t1 = new Thread(new ThreadStart(ThreadFunction));
            t1.Name = "T1";
            Thread t2 = new Thread(new ThreadStart(ThreadFunction));
            t2.Name = "T2";
            t1.Start();
            t2.Start();
            
            autoEvent.WaitOne(); // 等待两个线程都完成  
            Console.WriteLine("所有线程已完成。");
        }

        static void ThreadFunction()
        {
            Console.WriteLine(Thread.CurrentThread.Name + " 开始执行任务。");
            // 模拟任务执行时间  
            System.Threading.Thread.Sleep(3000);
            Console.WriteLine(Thread.CurrentThread.Name + " 任务完成。");
            // 发出唤醒信号给主线程  
            autoEvent.Set(); // 设置事件，唤醒等待的线程  
        }
    }
}
